package cn.neusoft.interceptor;

import cn.neusoft.util.TokenUtil;
import cn.neusoft.vo.ResponseObj;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        /*
        跨域请求有两次：
        第一次是OPTIONS请求   验证是否可以跨域请求  直接放行
        第二次是真正的请求
         */
        if("OPTIONS".equalsIgnoreCase(request.getMethod())){
            return true;
        }

        //1 登录拦截
        String token = request.getHeader("token");

        System.out.println("登录拦截的token："+token);

        if (token!=null && !"".equals(token)){
            Object loginUser = redisTemplate.opsForValue().get(token);
            //loginUser不为空  且验证通过 直接放行
            if (loginUser!=null){
                redisTemplate.opsForValue().set(token,loginUser,30, TimeUnit.MINUTES);
                return true;
            }
        }

        //2 权限拦截 //@TODO
        //都是登录是吧返回一个错误 {“success”:false,"message":"noLogin"}，让前端条页面
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=UTF-8");
        PrintWriter writer = response.getWriter();
        // 在外面写好在拷贝进去
        //把一个ResponseObj转成json
        ObjectMapper objectMapper = new ObjectMapper();
        String responseObjJson = objectMapper.writeValueAsString(ResponseObj.ERROR(501, "登录验证失败"));
        writer.write(responseObjJson);
        writer.close();
        return false;
    }
}